// app/controller/reconciliation_controller.js
'use strict';

const Controller = require('egg').Controller;
const Joi = require('joi');

class ReconciliationController extends Controller {
  // 获取对账结果列表 - 新增方法
  async getReconciliationResults() {
    const { ctx } = this;
    const { page = 1, limit = 20, status, customerName, startDate, endDate } = ctx.query;
    
    try {
      // 构建查询条件
      const where = {};
      
      if (status) {
        where.matchStatus = status;
      }
      
      if (startDate || endDate) {
        where.createdAt = {};
        if (startDate) {
          where.createdAt[ctx.app.Sequelize.Op.gte] = new Date(startDate);
        }
        if (endDate) {
          where.createdAt[ctx.app.Sequelize.Op.lte] = new Date(endDate);
        }
      }
      
      // 如果有客户名称查询条件，需要先查询客户ID
      let customerId = null;
      if (customerName) {
        const customer = await ctx.model.CustomerModel.findOne({
          where: {
            name: {
              [ctx.app.Sequelize.Op.like]: `%${customerName}%`
            }
          }
        });
        
        if (customer) {
          customerId = customer.id;
        } else {
          // 如果没找到客户，返回空结果
          ctx.page([], 0, parseInt(page), parseInt(limit));
          return;
        }
      }
      
      // 分页查询
      const offset = (parseInt(page) - 1) * parseInt(limit);
      
      // 构建包含销售订单和银行流水的查询
      const queryOptions = {
        where,
        order: [['matched_at', 'DESC']],
        limit: parseInt(limit),
        offset,
        include: [
          {
            model: ctx.model.SalesOrderModel,
            as: 'salesOrder',
            attributes: ['id', 'platformOrderId', 'orderAmount', 'orderDate'],
            ...(customerId ? { where: { customerId } } : {})
          },
          {
            model: ctx.model.BankTransactionModel,
            as: 'bankTransaction',
            attributes: ['id', 'transactionId', 'amount', 'transactionDate']
          }
        ]
      };
      
      const { rows, count } = await ctx.model.ReconciliationResultModel.findAndCountAll(queryOptions);
      
      ctx.page(rows, count, parseInt(page), parseInt(limit));
    } catch (error) {
      ctx.logger.error('获取对账结果列表失败:', error);
      ctx.error(`获取对账结果列表失败: ${error.message}`);
    }
  }
  
  // 生成智能分析报告
  async generateAnalysisReport() {
    const { ctx } = this;
    const {
      matchStatus,
      confidenceRange,
      customerName,
      reconciliationDateRange,
      maxAmountDiff,
      algorithm,
      operator,
      dataSource,
      includeDifferences
    } = ctx.query;
    
    try {
      // 使用Joi验证服务进行参数验证
      const schema = Joi.object({
        matchStatus: Joi.string().valid('matched', 'unmatched', 'partial', '').optional(),
        confidenceRange: Joi.array().items(Joi.number().min(0).max(100)).optional(),
        customerName: Joi.string().max(100).allow('').optional(),
        reconciliationDateRange: Joi.array().items(Joi.date().iso()).optional(),
        maxAmountDiff: Joi.number().positive().optional(),
        algorithm: Joi.string().max(50).allow('').optional(),
        operator: Joi.string().max(50).allow('').optional(),
        dataSource: Joi.string().max(50).allow('').optional(),
        includeDifferences: Joi.boolean().optional()
      });
      
      const validation = schema.validate({
        matchStatus,
        confidenceRange,
        customerName,
        reconciliationDateRange,
        maxAmountDiff,
        algorithm,
        operator,
        dataSource,
        includeDifferences
      });
      
      if (validation.error) {
        ctx.error(`参数验证失败: ${validation.error.message}`);
        return;
      }
      
      // 调用服务层生成分析报告
      const report = await ctx.service.smartReportService.generateReconciliationReport({
        matchStatus,
        confidenceRange,
        customerName,
        reconciliationDateRange,
        maxAmountDiff,
        algorithm,
        operator,
        dataSource,
        includeDifferences
      });
      
      ctx.success(report, '智能分析报告生成成功');
    } catch (error) {
      ctx.logger.error('生成智能分析报告失败:', error);
      ctx.error('生成智能分析报告失败: ' + error.message);
    }
  }
  
  // 获取对账报告数据 - 新增方法，专门为前端报告页面提供数据
  async getReconciliationReportData() {
    const { ctx } = this;
    const { startDate, endDate } = ctx.query;
    
    try {
      // 调用服务层获取对账报告数据
      const reportData = await ctx.service.smartReportService.getReconciliationReportData({
        startDate,
        endDate
      });
      
      ctx.success(reportData, '对账报告数据获取成功');
    } catch (error) {
      ctx.logger.error('获取对账报告数据失败:', error);
      ctx.error('获取对账报告数据失败: ' + error.message);
    }
  }
}

module.exports = ReconciliationController;